import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screen_lock/flutter_screen_lock.dart';

import 'package:pass_log/app/core/utils/encryption.dart';
import 'package:pass_log/app/data/providers/pass_provider.dart';

class LockController extends GetxController {
  var lockBox = Hive.box(name: "lock");
  static final plp = Get.find<PassListProvider>();

  @override
  void onInit() {
    super.onInit();
    if (!lockBox.containsKey("isCreate")) lockBox.put("isCreate", false);
  }

  @override
  void onReady() {
    super.onReady();
    if (lockBox.get("isCreate") && lockBox.containsKey("passHash")) {
      var passHash = lockBox.get("passHash");
      screenLock(
        context: Get.context!,
        correctString: "paslog", // 必填项，仅用于提示密码位数，密码判断逻辑在onValidate中
        title: const Text("请输入解锁密码"),
        cancelButton: const Text(""),
        canCancel: false, // 设置为false将禁用返回操作
        onValidate: (input) {
          if (generateHashString(input) == passHash) {
            Encryption.init(input); // 初始化加解密模块
            return Future.value(true);
          } else {
            return Future.value(false);
          }
        },
        onUnlocked: () {
          plp.refreshPass();
          lockBox.put("isLock", false); // 应用解锁状态
          Get.offAllNamed("/home");
        },
      );
    } else {
      screenLockCreate(
        context: Get.context!,
        title: const Text("请创建6位数的解锁密码"),
        confirmTitle: const Text("请再次输入您创建的密码"),
        cancelButton: const Text(""),
        canCancel: false,
        digits: 6, // 定义密码位数
        onConfirmed: (value) {
          var hashValue = generateHashString(value);
          Encryption.init(value);
          lockBox.put("isLock", false);
          lockBox.put("isCreate", true); // 应用密码创建状态
          lockBox.put("passHash", hashValue);
          Get.offAllNamed("/home");
        },
      );
    }
  }
}
